//
//  SAProductChooseColorView.m
//  yidiantong
//
//  Created by 黄志刚 on 2020/10/13.
//

#import "SAProductChooseColorView.h"
#import "SAProductChooseColorCell.h"
#import "SAProductChooseColorModel.h"
#import "SAProductChooseColorHeaderView.h"
#import "SAProductChooseColorHeaderView2.h"
#import "SAProductDeleteColorView.h"
#import "SAProductSizeORColorModel.h"
#import "SASpecsAttrToCheckAPI.h"
#import "SASpecsAttrListAPI.h"
#import "SASpecsAttrAddAPI.h"
#import "SASpecsAttrDelAPI.h"
#import "SAProductChooseColorModel.h"

@interface SAProductChooseColorView()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout, HTTPAPIDelegate,UITextFieldDelegate>

@property (nonatomic,strong) NSMutableArray *dataArray;
@property (nonatomic,strong) UICollectionView *collectionView;
@property (nonatomic ,copy) NSString *type;
@property (nonatomic ,assign) BOOL isDetail;
@property (nonatomic,strong) NSArray *detailArray;
@property (nonatomic,strong) NSArray *sizeOrColorArray;
@property (nonatomic ,assign) NSInteger productId;
@property (nonatomic,strong) UILabel *hitLabel;
@property (nonatomic,strong) UILabel *hitLabel1;
@property (nonatomic,strong) SASpecsAttrToCheckAPI *specsAttrToCheckAPI;
@property (nonatomic,strong) SASpecsAttrListAPI *specsAttrListAPI;
@property (nonatomic,strong) SASpecsAttrAddAPI *specsAttrAddAPI;
@property (nonatomic,strong) SASpecsAttrDelAPI *specsAttrDelAPI;
@property (nonatomic ,assign) BOOL isClear;

@property (nonatomic ,strong) NSMutableArray *selectMarr;
@property (nonatomic, strong) NSMutableArray *searchMarr;
@property (nonatomic, strong) UITextField *nameTextfiled;

@end

@implementation SAProductChooseColorView

+(instancetype)shareCornView {
    SAProductChooseColorView * shareView = [[SAProductChooseColorView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    return shareView;
}

-(instancetype)initWithFrame:(CGRect)frame
{
    if(self = [super initWithFrame:frame])
    {
        self.userInteractionEnabled = YES;
        self.backgroundColor = kColor(0, 0, 0, 0.6);
        self.isClear = NO;
        [self creatUI];
    }
    
    return self;
}

#pragma mark - HTTPAPIDelegate
- (void)fetchData:(id)data fromServerSuccessedWithAPI:(HTTPAPI *)api {
    if (self.specsAttrToCheckAPI == api) {
        [self.dataArray removeAllObjects];
        for ( NSDictionary *dict in (NSArray *)data[@"data"]) {
            SAProductChooseColorModel *model = [SAProductChooseColorModel mj_objectWithKeyValues:dict];
            [self.dataArray addObject:model];
        }
        [self textFieldEditChanged:self.nameTextfiled];
    }else if (self.specsAttrListAPI == api) {
        if (self.dataArray.count > 0) {
            [self.selectMarr removeAllObjects];
            for (SAProductChooseColorModel *model in self.dataArray) {
                for (SAProductChooseColorList *list in model.attrVOS) {
                    if (list.check == YES) {
                        NSString *specsAttrId = [NSString stringWithFormat:@"%@",list.specsAttrId];
                        [self.selectMarr addObject:specsAttrId];
                    }
                }
            }
        }
        [self.dataArray removeAllObjects];
        for ( NSDictionary *dict in (NSArray *)data[@"data"]) {
            SAProductChooseColorModel *model = [SAProductChooseColorModel mj_objectWithKeyValues:dict];
            for (SAProductChooseColorList *list in model.attrVOS) {
                if ([self.selectMarr containsObject:list.specsAttrId]) {
                    list.check = YES;
                }
            }
            [self.dataArray addObject:model];
        }
        [_collectionView reloadData];
    }else if (self.specsAttrAddAPI == api) {
        [Prompt popPromptViewWithMsg:@"新增成功!" duration:2];
        [self endEditing:YES];
        self.isClear = YES;
        [self.searchMarr removeAllObjects];
        self.nameTextfiled.text = @"";
        [self loadData];
    }else if (self.specsAttrDelAPI == api) {
        [Prompt popPromptViewWithMsg:@"删除成功!" duration:2];
        [self loadData];
    }
}

- (void)fetchDataFromServerFailedWithError:(NSError *)error API:(HTTPAPI *)api {
    
}


-(void)addBtnClick {
    if (self.nameTextfiled.text.length > 0) {
        self.specsAttrAddAPI.attrName = self.nameTextfiled.text;
        self.specsAttrAddAPI.specsType = self.type;
        [self.specsAttrAddAPI sendRequestToServerWithActivityViewAndMask:POST];
    }
}

#pragma mark - UITextFieldDelegate
- (void)textFieldEditChanged:(UITextField*)textField {
    [self.searchMarr removeAllObjects];
    if (textField.text.length > 0) {
        for (SAProductChooseColorModel *model in self.dataArray) {
            SAProductChooseColorModel *newModel = [SAProductChooseColorModel new];
            newModel.groupName = model.groupName;
            newModel.attrVOS = [NSMutableArray array];
            for (SAProductChooseColorList *attModel in model.attrVOS) {
                if ([attModel.attrName containsString:textField.text]) {
                    [newModel.attrVOS addObject:attModel];
                }
            }
            if (newModel.attrVOS.count > 0) {
                [self.searchMarr addObject:newModel];
            }
        }
        if (self.searchMarr.count == 0) {
            SAProductChooseColorModel *newModel = [SAProductChooseColorModel new];
            newModel.groupName = @"自定义";
            newModel.attrVOS = [NSMutableArray array];
            [self.searchMarr addObject:newModel];
        }
    }
    [self.collectionView reloadData];
}

-(void)creatUI
{
    UIButton *deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    deleteBtn.frame = CGRectMake(0, 0, kScreenWidth, kScaleNum(157));
    [deleteBtn addTarget:self action:@selector(shareDissTapEvent) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:deleteBtn];
    
    UIView *backGroundView = [[UIView alloc] initWithFrame:CGRectMake(0, kScaleNum(157), kScreenWidth, kScreenHeight - kScaleNum(157))];
    backGroundView.backgroundColor = kColor(246, 246, 246, 1);
    backGroundView.userInteractionEnabled = YES;
    [self addSubview:backGroundView];
    
    UIButton *confirmBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    confirmBtn.frame = CGRectMake(kScreenWidth - kScaleNum(80), kScaleNum(0), kScaleNum(80), kScaleNum(36));
    [confirmBtn setTitle:@"确认" forState:UIControlStateNormal];
    [confirmBtn setTitleColor:kBuleColor forState:UIControlStateNormal];
    [confirmBtn addTarget:self action:@selector(confirmationTapEvent) forControlEvents:UIControlEventTouchUpInside];
    confirmBtn.titleLabel.font = kFont(17);
    [backGroundView addSubview:confirmBtn];
    
    UIView *bgView = [[UIView alloc] initWithFrame:SARectMake(0, 36, kBaseScreenWidth, 36)];
    bgView.backgroundColor = [UIColor whiteColor];
    [backGroundView addSubview:bgView];
    
    UITextField *nameTextfiled = [[UITextField alloc] initWithFrame:SARectMake(22, 36, 200, 36)];
    nameTextfiled.autocapitalizationType = UITextAutocapitalizationTypeNone;
    nameTextfiled.clearButtonMode = UITextFieldViewModeWhileEditing;
    nameTextfiled.font = kFont(17);
    nameTextfiled.delegate = self;
    nameTextfiled.keyboardType = UIKeyboardTypeDefault;
    [nameTextfiled setTintColor:kColor(188, 188, 188, 1)];
    [nameTextfiled setTextColor:kColor(0, 0, 0, 1)];
    [nameTextfiled addTarget:self action:@selector(textFieldEditChanged:) forControlEvents:UIControlEventEditingChanged];
    self.nameTextfiled = nameTextfiled;
    [backGroundView addSubview:nameTextfiled];
    
    UIButton * addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    addBtn.frame = CGRectMake(kScreenWidth - kScaleNum(70), kScaleNum(39), kScaleNum(60), kScaleNum(30));
    [addBtn setImage:[UIImage imageNamed:@"Shop_CellAdd"] forState:UIControlStateNormal];
    [addBtn addTarget:self action:@selector(addBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [backGroundView addSubview:addBtn];
    
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
    // flow.headerReferenceSize = CGSizeMake(0, 200);
    flow.scrollDirection = UICollectionViewScrollDirectionVertical;
    flow.itemSize = CGSizeMake(kScaleNum(60), kScaleNum(24));
    flow.minimumInteritemSpacing = 0;
    //    //设置每行之间的最小间隔
    flow.minimumLineSpacing = kScaleNum(10);
    //   flow.headerReferenceSize = CGSizeMake(size(80), size(80));
    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(kScaleNum(0), kScaleNum(72), kScreenWidth,kScreenHeight - kScaleNum(229)) collectionViewLayout:flow];
    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.dataSource=self;
    _collectionView.delegate=self;
    _collectionView.showsVerticalScrollIndicator = NO;
    _collectionView.showsHorizontalScrollIndicator = NO;
    _collectionView.bounces = NO;
    [backGroundView addSubview:_collectionView];
    [_collectionView registerClass:[SAProductChooseColorCell class] forCellWithReuseIdentifier:@"SAProductChooseColorCell"] ;
    [_collectionView registerClass:[SAProductChooseColorHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"SAProductChooseColorHeaderView"];
    [_collectionView registerClass:[SAProductChooseColorHeaderView2 class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"SAProductChooseColorHeaderView2"];
    [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"UICollectionReusableView"];
    
    _hitLabel = [[UILabel alloc] init];
    _hitLabel1 = [[UILabel alloc] init];
}

-(void)loadData:(NSMutableArray *)array andType:(NSString *)type andIsDetail:(BOOL)isDetail andArray:(NSArray *)detailArray andType:(NSInteger)productId
{
    self.type = type;
    self.productId = productId;
    
    if ([_type isEqualToString:@"1"]) {
        self.hitLabel.text = @"请输入颜色名称";
        self.hitLabel1.text = @"【长按】可删除自定义颜色";
    }else
    {
        self.hitLabel.text = @"请输入尺码名称";
        self.hitLabel1.text =  @"【长按】可删除自定义尺码";
    }
    
    self.isDetail = isDetail;
    if (self.isDetail == YES) {
        self.detailArray = detailArray;
    }else
    {
        self.sizeOrColorArray = detailArray;
    }
    
    self.selectMarr = array; //记录选中的id 由于部分逻辑使用了ipad的内容，现在做兼容
    [self loadData];
}


-(void)loadData
{
    if (self.isDetail == YES) {
        self.specsAttrToCheckAPI.type = self.type;
        self.specsAttrToCheckAPI.productId = @(self.productId).stringValue;
        self.specsAttrToCheckAPI.iosIds = [self.selectMarr componentsJoinedByString:@","];
        [self.specsAttrToCheckAPI sendRequestToServerWithActivityViewAndMask:GET];
    }else
    {
        self.specsAttrListAPI.type = self.type;
        [self.specsAttrListAPI sendRequestToServerWithActivityViewAndMask:GET];
    }
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (self.searchMarr.count > 0) {
        SAProductChooseColorModel *model = self.searchMarr[section];
        return model.attrVOS.count;
    }
    SAProductChooseColorModel *model = self.dataArray[section];
    return model.attrVOS.count;
    
}
-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier=@"SAProductChooseColorCell";
    SAProductChooseColorCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    SAProductChooseColorModel *model = nil;
    if (self.searchMarr.count > 0) {
        model = self.searchMarr[indexPath.section];
    }else {
        model = self.dataArray[indexPath.section];
    }
    SAProductChooseColorList *list = model.attrVOS[indexPath.row];
    [cell loadData:list];
    if (indexPath.section == 0) {
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(moveCollectionViewCell:)];
        [cell addGestureRecognizer:longPress];
    }
    return cell;
    
}
#pragma mark - 手势事件
-(void)moveCollectionViewCell:(UILongPressGestureRecognizer *)gesture {
    switch (gesture.state) {
        case UIGestureRecognizerStateBegan: {
            
            CGPoint point = [gesture locationInView:self.collectionView];
            NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:point];
            if (indexPath.section != 0) {
                return;
            }
            SAProductChooseColorModel *model = nil;
            if (self.searchMarr.count > 0) {
                model = self.searchMarr[0];
            }else {
                model = self.dataArray[0];
            }
            if (![model.groupName isEqualToString:@"自定义"]) {
                return;
            }
            SAProductChooseColorList *list = model.attrVOS[indexPath.row];
            
            if (self.isDetail == YES) {
                if (list.canCancel == NO) {
                    if ([_type isEqualToString:@"1"]) {
                        [Prompt popPromptViewWithMsg:@"该颜色已有库存,无法删除" duration:2];
                        return;
                    }else
                    {
                        [Prompt popPromptViewWithMsg:@"该尺码已有库存,无法删除" duration:2];
                        return;
                    }
                }
            }
            if (self.sizeOrColorArray.count >0) {
                for (SAProductSizeORColorModel *sizeORColorModel in self.sizeOrColorArray) {
                    if (list.specsAttrId == sizeORColorModel.colorId) {
                        [Prompt popPromptViewWithMsg:@"该颜色已有库存,无法删除" duration:2];
                        return;
                    }
                    if (list.specsAttrId == sizeORColorModel.sizeId) {
                        [Prompt popPromptViewWithMsg:@"该尺码已有库存,无法删除" duration:2];
                        return;
                    }
                }
            }
            
            SAProductDeleteColorView *deleteColorView= [SAProductDeleteColorView shareCornView];
            deleteColorView.deleteColorBlock = ^{
                self.specsAttrDelAPI.specsAttrId = list.specsAttrId;
                [self.specsAttrDelAPI sendRequestToServerWithActivityViewAndMask:POST];
            };
            [deleteColorView setString:list.attrName];
            UIViewController *view = nil;
            [deleteColorView showView:view];
            break;
        }
        case UIGestureRecognizerStateChanged: {
            break;
        }
        case UIGestureRecognizerStateEnded: {
        }
        default:
            [self.collectionView cancelInteractiveMovement];
            break;
    }
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    if (self.searchMarr.count > 0) {
        return self.searchMarr.count;
    }
    return self.dataArray.count;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    SAProductChooseColorModel *model = nil;
    if (self.searchMarr.count > 0) {
        model = self.searchMarr[indexPath.section];
    }else {
        model = self.dataArray[indexPath.section];
    }
    SAProductChooseColorList *list = model.attrVOS[indexPath.row];
    
    if (self.isDetail == YES) {
        if (list.canCancel == NO) {
            if ([_type isEqualToString:@"1"]) {
                [Prompt popPromptViewWithMsg:@"该颜色已有库存,无法取消" duration:2];
                return;
            }else
            {
                [Prompt popPromptViewWithMsg:@"该尺码已有库存,无法取消" duration:2];
                return;
            }
        }
    }
    
    
    BOOL isTag = NO;
    if (self.sizeOrColorArray.count >0) {
        for (SAProductSizeORColorModel *sizeORColorModel in self.sizeOrColorArray) {
            if (list.specsAttrId == sizeORColorModel.colorId) {
                isTag = YES;
                [Prompt popPromptViewWithMsg:@"该颜色已有库存,无法取消" duration:2];
            }
            if (list.specsAttrId == sizeORColorModel.sizeId)
            {
                isTag = YES;
                [Prompt popPromptViewWithMsg:@"该尺码已有库存,无法取消" duration:2];
            }
        }
    }
    if (isTag == NO) {
        list.check = !list.check;
    }
    
    [self.collectionView reloadData];
    
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    //返回段头段尾视图
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        SAProductChooseColorModel *model = nil;
        if (self.searchMarr.count > 0) {
            model = self.searchMarr[indexPath.section];
        }else {
            model = self.dataArray[indexPath.section];
        }
        if (indexPath.section == 0 && [model.groupName isEqualToString:@"自定义"]) {
            SAProductChooseColorHeaderView2 *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"SAProductChooseColorHeaderView2" forIndexPath:indexPath];
            [headerView refreshWithTitle:model.groupName Placeholder: self.hitLabel.text AndTip:self.hitLabel1.text];
            if (self.isClear == YES) {
                self.isClear = NO;
            }
            return headerView;
        }else {
            SAProductChooseColorHeaderView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"SAProductChooseColorHeaderView" forIndexPath:indexPath];
            headerView.hitLabel.text = model.groupName;
            return headerView;
        }
    }else {
        UICollectionReusableView *footView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"UICollectionReusableView" forIndexPath:indexPath];
        return footView;
    }
    return nil;
}

- (CGSize)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return CGSizeMake(kScreenWidth, kScaleNum(32));
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    if (section == self.dataArray.count - 1) {
        return CGSizeMake(kScreenWidth, kScaleNum(34));
    }
    return CGSizeMake(kScreenWidth, 0);
}

#pragma mark--UICollectionViewDelegateFlowLayout的协议方法

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(kScaleNum(10), kScaleNum(10),kScaleNum(10),kScaleNum(10));
}

-(NSMutableArray *)dataArray
{
    if(_dataArray == nil)
    {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

-(NSMutableArray *)searchMarr {
    if (!_searchMarr) {
        _searchMarr = [NSMutableArray array];
    }
    return _searchMarr;
}


- (void)showView:(UIViewController *)Sview
{
    if(Sview==nil){
        
        [[UIApplication sharedApplication].keyWindow addSubview:self];
        
    }else{
        //[view addSubview:self];
        [Sview.view addSubview:self];
    }
}

-(void)shareDissTapEvent
{
    [UIView animateWithDuration:0.5f animations:^{
        
        self.alpha = 0.0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

-(void)confirmationTapEvent
{
    
    //    NSMutableArray *seleArray = [NSMutableArray new];
    //    for (SAProductChooseColorModel *model in self.dataArray) {
    //
    //        for ( SAProductChooseColorList *list in model.attrVOS) {
    //            if (list.check == YES) {
    //               [seleArray addObject:list];
    //            }
    //
    //        }
    //    }
    if (self.selectedBlock) {
        self.selectedBlock(self.dataArray);
    }
    
    [UIView animateWithDuration:0.5f animations:^{
        
        self.alpha = 0.0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

-(SASpecsAttrToCheckAPI *)specsAttrToCheckAPI {
    if (!_specsAttrToCheckAPI) {
        _specsAttrToCheckAPI = [SASpecsAttrToCheckAPI apiWithDelegate:self];
    }
    return _specsAttrToCheckAPI;
}

-(SASpecsAttrListAPI *)specsAttrListAPI {
    if (!_specsAttrListAPI) {
        _specsAttrListAPI = [SASpecsAttrListAPI apiWithDelegate:self];
    }
    return _specsAttrListAPI;
}

-(SASpecsAttrAddAPI *)specsAttrAddAPI {
    if (!_specsAttrAddAPI) {
        _specsAttrAddAPI = [SASpecsAttrAddAPI
                            apiWithDelegate:self];
    }
    return _specsAttrAddAPI;
}

-(SASpecsAttrDelAPI *)specsAttrDelAPI {
    if (!_specsAttrDelAPI) {
        _specsAttrDelAPI = [SASpecsAttrDelAPI apiWithDelegate:self];
    }
    return _specsAttrDelAPI;
}

@end
